#ifndef __THREAD_TOOL_H__
#define __THREAD_TOOL_H__

#include <stdio.h>
#include <stdlib.h>

#if defined(__WIN_PLATFORM__)
#undef USE_THREADS_POSIX
#define USE_THREADS_WIN
#elif __LINUX_PLATFORM__
#undef USE_THREADS_WIN
#define USE_THREADS_POSIX
#endif /*__WIN_PLATFORM__*/

#if defined(USE_THREADS_POSIX)
#	include <pthread.h>
#elif defined(USE_THREADS_WIN)
//#	include <Winsock2.h>
#	include <windows.h>
#	include <process.h>
#endif

//using namespace std;


#if defined(USE_THREADS_POSIX)
#  define SELF_STDCALL
#  define self_mutex_t           pthread_mutex_t
#  define self_thread_t          pthread_t
#  define self_thread_t_null     (pthread_t)0
#  define self_mutex_init(m)     pthread_mutex_init(m, NULL)
#  define self_mutex_acquire(m)  pthread_mutex_lock(m)
#  define self_mutex_release(m)  pthread_mutex_unlock(m)
#  define self_mutex_destroy(m)  pthread_mutex_destroy(m)
#elif defined(USE_THREADS_WIN)
#  define SELF_STDCALL           __stdcall
#  define self_mutex_t           CRITICAL_SECTION
#  define self_thread_t          HANDLE
#  define self_thread_t_null     (HANDLE)0
#  define self_mutex_init(m)     InitializeCriticalSection(m)
#  define self_mutex_acquire(m)  EnterCriticalSection(m)
#  define self_mutex_release(m)  LeaveCriticalSection(m)
#  define self_mutex_destroy(m)  DeleteCriticalSection(m)
#endif

extern self_thread_t self_thread_create(unsigned int (SELF_STDCALL *func) (void*),
                                 void *arg);

extern void self_thread_destroy(self_thread_t hnd);

extern int self_thread_join(self_thread_t *hnd);


class ThreadTool
{
public:
	ThreadTool(void);
	virtual ~ThreadTool(void);
};

class ScopeLock
{
public:
	ScopeLock(self_mutex_t &lock) :mLock(lock)
	{ 
		self_mutex_init(&mLock);
		self_mutex_acquire(&mLock);
	}
	~ScopeLock()
	{
		self_mutex_release(&mLock);
		self_mutex_destroy(&mLock);
	}
private:
	self_mutex_t mLock;
};

class AutoLock
{
public:
	AutoLock(self_mutex_t &lock) :mLock(lock)
	{ 
		self_mutex_acquire(&mLock);
	}
	~AutoLock()
	{
		self_mutex_release(&mLock);
	}
private:
	self_mutex_t mLock;
};

#endif /*__THREAD_TOOL_H__*/


